import _thread
from fastapi import FastAPI
import time
import random
import math

app = FastAPI()
ID_Yolo = []
ID_Iot = []
Sucess_Bingding_IOTID = []
Sucess_Bingding_yoloID = []
xy_yolo = {}
MUSICID = {}
# 以耳机的编号为主参数
InterestedXY = {}
InterestedXY[0] = {'lux': 395, 'luy': 778, 'rdx': 542, 'rdy': 883}
InterestedXY[1] = {'lux': 1078, 'luy': 170, 'rdx': 1182, 'rdy': 610}

InterestedID = {}  ## 这里检测是是以iot编号为键值的感兴趣的秒数
limit_x = 50
limit_y = 50


def log(fn, n, a):
    return 0


@app.get('/yolo')
def GetinformationFromYolo(ID, x, y, w, h):
    global ID_Yolo
    ID_Yolo.insert(0, int(ID))
    ID_Yolo = list(set(ID_Yolo))
    xy_yolo[int(ID)] = {'x': int(x), 'y': int(y), 'w': int(w), 'h': int(h)}


def WaitingForReplace():
    return 0


def Isinteresting(fiot, x, y, w, h):
    global MUSICID
    People_mid_x = (x + w + x) / 2
    People_mid_y = (y + h + y) / 2
    # InterestedID[fiot] = fiot #fiot为了区别局部变量和全局变量
    for i in InterestedXY:
        tempIns = InterestedXY[i]
        mid_x = (tempIns['lux'] + tempIns['rdx']) / 2
        mid_y = (tempIns['luy'] + tempIns['rdy']) / 2
        distance = math.sqrt(pow((People_mid_y - mid_y), 2) + pow((People_mid_x - mid_x), 2))

        if distance <= 350:
            try:
                InterestedID[fiot] = InterestedID[fiot] + 1
            except:
                InterestedID[fiot] = fiot
            if InterestedID[fiot] - fiot >= 3:  # 判断停留时间
                MUSICID[fiot] = int(i)
                InterestedID[fiot] = fiot

    return 0


def working(yolo, iot):
    while True:
        Isinteresting(iot, xy_yolo[yolo]['x'], xy_yolo[yolo]['y'], xy_yolo[yolo]['w'], xy_yolo[yolo]['h'])
        time.sleep(1)
    return 0


def Binding_Success(id, id1):
    _thread.start_new_thread(working, (id, id1,))


def Binding(id):
    global Sucess_Bingding_yoloID
    global ID_Iot
    global ID_Yolo
    try:
        yolo = ID_Yolo.pop()
        if yolo in Sucess_Bingding_yoloID:
            return 0
        iot = ID_Iot.pop()
        Binding_Success(yolo, iot)
        Sucess_Bingding_yoloID.insert(0, yolo)
        return 1
    except:
        temp = 0
    return temp


def Isinterested(id, x, y, w, ):
    return 0


# Wait for Json -X-Y

def GetMusicID(id):
    return MUSICID[id]


@app.get('/')
def Index(ID: int = None, Status: int = None):
    global MUSICID
    if (Status == 0):
        res = "binding_status:" + str(Binding(ID))
        for i in ID_Iot:
            if (i == ID):
                return res
        ID_Iot.insert(0, ID)
        return res
    try:
        test = MUSICID[ID]
        res = "binding_status:" + "1" + "music_id:" + str(MUSICID[ID])
    except:
        res = "binding_status:" + "1" + "music_id:" + "255"
    return res


if __name__ == '__main__':
    import uvicorn

    uvicorn.run(app=app,
                host='0.0.0.0',
                port=8888,
                workers=1)